package com.servlet.contacts;

import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.listener.ContextListener;
import com.servlet.form.Format;
import com.servlet.model.base.Profile;
import com.servlet.model.database.BaseAcces;

/**
 * Servlet appelée lors de l'ajout d'un contact depuis la page de news
 * @author Marc Bouffard
 */
public class AjouterContact extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{	
		HttpSession session = request.getSession();
		
		BaseAcces base = ContextListener.base;
		String email = (String) session.getAttribute("email");

		if( request.getParameter("numR") != null )
		{
			int num = Integer.parseInt( request.getParameter("numR") );
	
			TreeSet<Profile> a = (TreeSet<Profile>)(session.getAttribute("rechercheAppuie"));
	
			//session.setAttribute("rechercheAppuie",  null );
	
			Profile[] ares = a.toArray(new Profile[0]);
	
			java.util.Date dd = Calendar.getInstance().getTime();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dat = dateFormat.format(dd);
			Date date = Date.valueOf(dat);
	
			base.addContact( email , ares[num].getEmail()  , date );
	
			base.addNews( email , ares[num].getEmail() , date, 1 );
			
			ares[num].setMode(1);
	
			response.sendRedirect("explorer?indice=" + session.getAttribute("numero_page"));
		}
		else if( request.getParameter("numS") != null )
		{
			int num = Integer.parseInt( request.getParameter("numS") );
			
			TreeSet<Profile> a = (TreeSet<Profile>)(session.getAttribute("selectionAppuie"));
	
			session.setAttribute("selectionAppuie",  null );
	
			Profile[] ares = a.toArray(new Profile[0]);
	
			java.util.Date dd = Calendar.getInstance().getTime();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dat = dateFormat.format(dd);
			Date date = Date.valueOf(dat);
	
			base.addContact( email , ares[num].getEmail()  , date );
	
			base.addNews( email , ares[num].getEmail() , date, 1 );
	
			response.sendRedirect("suggestion?indice=" + session.getAttribute("numero_page"));
		}
	}
}
